using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SPSolutions.Samples.PickerApp.WebControls
{
    /// <summary>
    /// Represents a site editor entry
    /// </summary>
    public class CityEditor : EntityEditorWithPicker
    {
        // Fields
        private Hashtable m_matchingEntities = new Hashtable(StringComparer.Create(CultureInfo.InvariantCulture, true));
        private string m_commaSeparatedCityDelayedUntilOnInit;
        private bool m_hasOnInitBeenCalled = false;

        /// <summary>
        /// Comma seperated webs
        /// </summary>
        public string CommaSeparatedCity
        {
            get { return GetResolvedEntityCity(); }
            set
            {
                if (HasOnInitBeenCalled)
                {
                    UpdateEntities(GetCityEntities(value));
                }
                else
                {
                    m_commaSeparatedCityDelayedUntilOnInit = value;
                }
            }
        }

        /// <summary>
        /// True if the OnInit method has already been called
        /// </summary>
        public bool HasOnInitBeenCalled
        {
            get { return m_hasOnInitBeenCalled; }
            set { m_hasOnInitBeenCalled = value; }
        }

        /// <summary>
        /// Get requested state
        /// </summary>
        public string RequestedState
        {
            get
            {
                if (string.IsNullOrEmpty(Page.Request.QueryString["State"]))
                {
                    return "TN";
                }
                return Page.Request.QueryString["State"];
            }
        }

        /// <summary>
        /// Init control
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PickerDialogType = typeof(CityPickerDialog);

            #region Initialize data
            HasOnInitBeenCalled = true;
            if (!string.IsNullOrEmpty(m_commaSeparatedCityDelayedUntilOnInit))
            {
                UpdateEntities(GetCityEntities(m_commaSeparatedCityDelayedUntilOnInit));
                m_commaSeparatedCityDelayedUntilOnInit = null;
            }
            #endregion
        }

        /// <summary>
        /// Convert a SPWeb to a picker entity
        /// </summary>
        /// <param name="web"></param>
        /// <returns></returns>
        private PickerEntity ConvertCityToPickerEntity(City city)
        {
            // Create new picker entity
            PickerEntity entity = new PickerEntity();

            // Set default attributes
            entity.Key = city.Name;
            entity.DisplayText = city.Name;
            entity.Description = city.State;

            // Set extended properties
            if (!string.IsNullOrEmpty(city.State))
            {
                entity.EntityData[CityInfo.State] = city.State;
            }

            // Return entity
            return entity;
        }

        /// <summary>
        /// Get a list of resolved entity webs
        /// </summary>
        /// <returns></returns>
        public string GetResolvedEntityCity()
        {
            // Create array
            StringBuilder builder = new StringBuilder(100);

            // Loop entities
            foreach (PickerEntity entity in base.ResolvedEntities)
            {
                // Append seperator
                if (builder.Length > 0)
                    builder.Append(",");

                // Append key
                builder.Append(entity.Key);
            }

            // Return list of web names
            return builder.ToString();
        }

        /// <summary>
        /// Get web description
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public string GetCityDescription(PickerEntity entity)
        {
            return entity.Key;
        }

        /// <summary>
        /// Get city entities
        /// </summary>
        /// <param name="commaSeparatedCity"></param>
        /// <returns></returns>
        public ArrayList GetCityEntities(string commaSeparatedCity)
        {
            ArrayList list = new ArrayList();
            if (commaSeparatedCity != null)
            {
                foreach (string text in commaSeparatedCity.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries))
                {
                    string text2 = text.Trim();
                    if (!string.IsNullOrEmpty(text2))
                    {
                        PickerEntity entity = new PickerEntity();
                        entity.Key = text2;
                        list.Add(entity);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// Resolve search text into a collection of picker entities
        /// </summary>
        /// <param name="unresolvedText"></param>
        /// <returns></returns>
        protected override PickerEntity[] ResolveErrorBySearch(string unresolvedText)
        {
            return base.ResolveErrorBySearch(unresolvedText);
        }

        /// <summary>
        /// Validate picker entity
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public override PickerEntity ValidateEntity(PickerEntity entity)
        {
            // This entity is already resolved
            if (entity.IsResolved)
            {
                return entity;
            }

            // Get the city
            City city = CityManager.AllCities.GetCityNoThrow(entity.Key);

            // No city found
            if (city == null)
            {
                return entity;
            }

            // Resolve entity
            entity = ConvertCityToPickerEntity(city);
            entity.IsResolved = true;

            // Return entity
            return entity;
        } 

        #region Web Info Struct

        /// <summary>
        /// Represents a list of attributes used by the picker entity for a city
        /// </summary>
        public struct CityInfo
        {
            /// <summary>
            /// City id attribute key
            /// </summary>
            public static readonly string CityId = "CityId";

            /// <summary>
            /// Title attribute key
            /// </summary>
            public static readonly string Title = "Title";

            /// <summary>
            /// State attribute key
            /// </summary>
            public static readonly string State = "State";
        }

        #endregion

    }
}
